<?php
/**
 * Copyright (c) 2010, Slawomir Mazur <mazursllawek@gmail.com>
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions 
 * are met:
 * 
 * o Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * o Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * o Neither the name of the Softisland nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * Enter description here...
 *
 * @package     Cms
 * @subpackage  Cms_Index
 * @copyright   Slawomir Mazur (c) 2010 (http://www.zend.com/zce.php?c=ZEND011643)
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @author      Slawomir Mazur <mazursllawek@gmail.com>
 */

class IndexController extends Zend_Controller_Action
{
	private $_navigationSession;
	
	public function init()
	{
		$this->_navigationSession = new Zend_Session_Namespace('navigationSession');
	}

    public function indexAction()
    {
    	$this->_navigationSession->backURL = $this->view->baseUrl('/');
    	$this->_navigationSession->attributesToSelect = array();
    }
    
    public function resultAction()
    {
    	if (!($query = $this->getRequest()->getParam('q', false)) ||
    		!($attribute = $this->getRequest()->getParam('a', false))) { 
    		
			$this->_helper->getHelper(Gp_View_Helper_Messenger::FRONTEND_MESSENGER)
					->addError($this->view->translate('Empty query!'));    				
    		$this->_redirect('index');
    	}
    	
    	$year = $this->getRequest()->getParam('y', Gp_View_Helper_Library::LATEST);
    	
    	$matches = array();    	
    	preg_match_all('#[a-zA-Z0-9\-\_]+#', $query, $matches);
    	
    	// attributes to select. This will be set to empty only in indexAction
    	if (empty($this->_navigationSession->attributesToSelect)) {
    		$this->_navigationSession->attributesToSelect = $this->getRequest()->getParam('ae', array());
    	}
    	
    	// empty query
    	if (0 == count($matches[0])) {
    		$this->_helper->getHelper(Gp_View_Helper_Messenger::FRONTEND_MESSENGER)
					->addError($this->view->translate('Empty query!'));    				
    		$this->_redirect('index');

    	// single (standard) query
    	} else if (1 == count($matches[0])) {
    		$this->_singleQuery(trim($matches[0][0]), $attribute, $year);
    		
	   	// multi query
    	} else {
    		$this->_multiQuery($matches[0], $attribute, $year);
    	}
    }
    
    private function _singleQuery($query, $attribute, $year)
    {
    	/* @var $model System_Model_History */
    	$model = Gp_App::getModel('system/history');
    	$result = $model->loadMostUpdateGeneData($query, $attribute, $year);
    	
    	$outputData = array();
    	foreach ($result as $historyEntry) {
    		if (!isset($outputData[$historyEntry->library_id])) {
    			$outputData[$historyEntry->library_id] = array();
    		}
    		$outputData[$historyEntry->library_id][] = $historyEntry;
    	}    	
    	$this->view->collection = $outputData;
    	
    	// query data
    	$this->view->attributeId = $attribute;
    	$this->view->query = $query;
    	$this->view->year = $year;
    	
    	// set back URL
    	$this->_navigationSession->backURL = $this->view->baseUrl('/index/result/q/' . $query . '/a/' . $attribute);
    	
    	$this->renderScript('index/result.phtml');
    } 
    
    private function _multiQuery(array $queries = array(), $attribute, $year)
    {    	
    	$totalResults = array();
    	
    	/* @var $model System_Model_History */
    	$model = Gp_App::getModel('system/history');
    	
    	foreach ($queries as $query) {    		
    		$result = $model->loadMostUpdateGeneData($query, $attribute, $year);
	    	
	    	$outputData = array();
	    	foreach ($result as $historyEntry) {
	    		if (!isset($outputData[$historyEntry->library_id])) {
	    			$outputData[$historyEntry->library_id] = array();
	    		}
	    		$outputData[$historyEntry->library_id][] = $historyEntry;
	    	}
	    	$totalResults[$query] = $outputData;
    	}    	
    	$this->view->collection = $totalResults;
    	
    	// query data
    	$this->view->attributeId = $attribute;
    	$this->view->year = $year;
    	
		// set back URL
    	$this->_navigationSession->backURL = $this->view->baseUrl('/index/result/q/' . join(',',$queries) . '/a/' . $attribute);
    	
    	$this->renderScript('index/multiResult.phtml');
    }
    
    public function libraryHistoryAction()
    {
    	// query data
    	$companyId = $this->getRequest()->getParam('cid', false);
    	$query = $this->getRequest()->getParam('q', false);
    	$attributeId = $this->getRequest()->getParam('aid', false);
    	$year = $this->getRequest()->getParam('year', false);
    	
    	try {
    		if (empty($companyId) || empty($query) || empty($attributeId)) {
    			throw new Exception('Some data for query is missing');
    		}			
			
    		$geneHistoryObject = Gp_App::getModel('system/library')
    					->getLibrariesHistoryByCompanyIdSQL($companyId, $query, $attributeId, $year);
			
    		$this->view->companyId = $companyId;
			$this->view->data = $geneHistoryObject->rows;
			
			// navigation
			$this->view->navigation = isset($geneHistoryObject->navigation) ? $geneHistoryObject->navigation : false;
			
			// data for back link
			$this->view->aid = $attributeId;
			$this->view->q = $query;
			$this->view->year = $year;
			
			// set back URL
			$this->view->backURL = $this->_navigationSession->backURL;
			
    	} catch (Exception $e) {    		
    		$this->_helper->getHelper(Gp_View_Helper_Messenger::FRONTEND_MESSENGER)
    				->addError($this->view->translate($e->getMessage()));
    		$this->_redirect('index');
    	}
    }
        
    public function networkAction()
    {
    	// head script data
    	$headScripts = $this->view->headScript();

    	$headScripts->appendFile($this->view->baseUrl('js/cytoscape/json2.min.js'));
    	$headScripts->appendFile($this->view->baseUrl('js/cytoscape/AC_OETags.min.js'));
		$headScripts->appendFile($this->view->baseUrl('js/cytoscape/cytoscapeweb.min.js'));
		
		$gene = $this->getRequest()->getParam('gene', null);
		$libraryId = $this->getRequest()->getParam('library', null);
		
		try {
			if (is_null($gene) || is_null($libraryId)) {
				throw new Exception('Empty library id or gene id');
			}
			/* @var $network System_Model_Network */
			$network = Gp_App::getModel('system/network');
			$networkFile = $network->generateNetworkForLibrary($libraryId, $gene);
			
			// init source
			$this->view->networkSource = $networkFile;			

			$this->view->gene = $gene;
			$this->view->library = $libraryId;
			
			// set back URL
			$this->view->backURL = $this->_navigationSession->backURL;
			
		} catch (Exception $e) {
			$this->_helper->getHelper(Gp_View_Helper_Messenger::FRONTEND_MESSENGER)
    				->addError($this->view->translate($e->getMessage()));
    		$this->_redirect('index');
		}
    }
    
    public function aboutAction()
    {
    	
    }
    
	public function collaboratorAction()
    {
    	
    }
    
	public function seedseqAction()
    {
    	
    }
    
	public function newsAction()
    {
    	
    }
    
	public function contactAction()
    {
    	
    }
}